const domain = "https://hsh.bakebao.com";
const md5 = require("md5.js");
var QQMapWX = require('/qqmap-wx-jssdk.js');
var qqmapsdk;
qqmapsdk = new QQMapWX({
  key: '4W7BZ-AHPH6-I76ST-MAFFV-JJID5-DQBJ4'
});
const FormatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const FormatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
String.prototype.RHtml = function () {
  return this.replace(/<[^>]+>/g, "").replace(/&nbsp;/g, "");
};

String.prototype.ReplaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
};

Array.prototype.Remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};

Array.prototype.RemoveAt = function (n) {
  if (n < 0)
  { return this; }
  else
  { return this.slice(0, n).concat(this.slice(n + 1, this.length)); }
};

Array.prototype.indexOf = function (val) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == val) return i;
  }
  return -1;
};

Array.prototype.Max = function () {
  return Math.max.apply(Math, this);
};

Array.prototype.Min = function () {
  return Math.min.apply(Math, this);
};

String.prototype.ToDate = function () {
  var date = new Date(this.replace(/-/g, "/"));
  return date.Format("MM.dd");
};

Date.prototype.Format = function (format) {
  var o = {
    "M+": this.getMonth() + 1, //month 
    "d+": this.getDate(), //day 
    "h+": this.getHours(), //hour 
    "m+": this.getMinutes(), //minute 
    "s+": this.getSeconds(), //second 
    "q+": Math.floor((this.getMonth() + 3) / 3), //quarter 
    "S": this.getMilliseconds() //millisecond 
  };
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
  }
  return format;
};

function Ajax(data, callback) {
  data.sign = md5.GetSign(data.act);
  data.token = '38BA0ECC38121613';
  wx.request({
    url: domain + '/tools/API.ashx',
    data: data,
    header: {
      'content-type': 'application/json'
    },
    success: function (res) {
      wx.hideLoading();
      if (callback) {
        callback(res.data)
      }
    },
    fail: function (res) {
      wx.hideLoading();
      ShowError("网络已经中断");
    }
  })
};
function Upload(path, data, callback) {
  wx.uploadFile({
    url: domain + '/tools/Upload.ashx',
    filePath: path,
    name: 'img',
    formData: data,
    success: function (res) {
      if (callback) {
        callback(res.data)
      }
    }
  });
}
function ShowError(title) {
  wx.showToast({
    title: title,
    image: '/image/error.png'
  });
};
function ShowSuccess(title) {
  wx.showToast({
    title: title
  });
};
function ShowLoading(title) {
  wx.showLoading({
    title: title
  });
};
function GetAddressByPosition(latitude, longitude, callback) {  //根据经纬度 获取省市区
  qqmapsdk.reverseGeocoder({
    location: {
      latitude: latitude,
      longitude: longitude
    },
    success: function (res) {
      callback(res);
    },
    fail: function (res) {
      //console.log(res);
    },
    complete: function (res) {
      callback(res);
    }
  });
}
function GetAddressByNameAndCity(name, city, callback) { //根据名称和城市模糊查询 信息
  var that = this;
  qqmapsdk.getSuggestion({
    keyword: name,
    region: city,
    region_fix: 1, //取值： 0：[默认]当前城市无结果时，自动扩大范围到全国匹配 1：固定在当前城市
    success: function (res) {
      //console.log(res.data);
      callback(res);
    },
    fail: function (res) {
      //console.log(res);
    },
    complete: function (res) {
      //console.log(res.data);
      callback(res);
    }
  });
}
function GetPositionByName(name, callback) {  //根据道路名称获取经纬度
  qqmapsdk.geocoder({
    address: name,
    success: function (res) {
      callback(res);
    },
    fail: function (res) {
      //console.log(res);
    },
    complete: function (res) {
      //console.log(res);
      callback(res);
    }
  });
}
function GetUserInfo(error) { //获取用户信息
  var that = this;
  wx.login({
    success: res => {
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      wx.request({
        url: domain + '/tools/API.ashx?act=GetOpenID&code=' + res.code,
        method: 'GET',
        header: {
          'content-type': 'application/json' // 默认值
        },
        success: function (openIdRes) {
          wx.setStorageSync('openids', openIdRes.data);

          wx.login({
            success: function (res) {
              wx.getUserInfo({
                lang: "zh_CN",
                success: function (userRes) {
                  AddUserInfo(userRes);
                },
                fail: function () {
                  wx.showModal({
                    title: '警告',
                    content: error,
                    success: function (res) {
                      if (res.confirm) {
                        wx.openSetting({
                          success: function (datas) {
                            if (datas.authSetting["scope.userInfo"]) {
                              wx.getUserInfo({
                                success: function (res) {
                                  AddUserInfo(res);
                                }
                              })
                            } else {
                              that.GetUserInfo(error);
                            }
                          }
                        })
                      } else {
                        that.GetUserInfo(error);
                      }
                    },
                    fail: function () { }
                  })
                }
              })
            }
          })
        }
      })

    }
  })
}
function AddUserInfo(userinfo) {  //保存用户访问信息
  var that = this;
  var openid = '';
  wx.getStorage({
    key: 'openids',
    success: function (res) {
      openid = res.data;
      var data = {
        openid: openid,
        nickname: userinfo.userInfo.nickName,
        headimg: userinfo.userInfo.avatarUrl,
        province: userinfo.userInfo.province,
        city: userinfo.userInfo.city,
        sex: userinfo.userInfo.gender
      };
      data.act = "Save_User";
      Ajax(data, function (json) {
        wx.setStorageSync('UserID', json.data)  //保存用户ID
        wx.setStorageSync('NickName', data.nickname)  //保存微信昵称
        wx.setStorageSync('HeadImg', data.headimg)  //保存头像
      });
    }
  })
}
function GetAddress() {  //获取地理位置
  var that = this;
  wx.getLocation({
    type: 'gcj02',
    success: function (res) {
      AddressInfo(res);
    },
    fail: function () {
      wx.showModal({
        title: '警告',
        content: '您点击了拒绝授权,将无法正常地理位置信息,点击确定重新获取授权。',
        success: function (res) {
          //console.log(res);
          if (res.confirm) {
            wx.openSetting({
              success: function (datas) {
                if (datas.authSetting["scope.userLocation"]) {
                  wx.getLocation({
                    success: function (res) {
                      //AddressInfo(res);
                      console.log("已经授权了");
                      //home.GetSupplierList(res.latitude, res.longitude); //重新加载优惠商家
                    }
                  })
                } else {
                  GetAddress();
                }
              }
            })
          } else {
            GetAddress();
          }
        },
        fail: function () { }
      })
    }
  })
}

module.exports = {
  Domain: domain,
  FormatTime: FormatTime,
  Ajax: Ajax,
  Upload: Upload,
  ShowSuccess: ShowSuccess,
  ShowError: ShowError,
  ShowLoading: ShowLoading,
  GetAddressByPosition: GetAddressByPosition,
  GetAddressByNameAndCity: GetAddressByNameAndCity,
  GetPositionByName: GetPositionByName,
  GetUserInfo: GetUserInfo,
  GetAddress: GetAddress
}
